import { GTRequestInterface } from './types'
import { Toast } from 'vant'
import { errorResult } from '../Axios'
import { GTAxiosOptions } from '../types'

class GTRequest implements  GTRequestInterface {

  axiosOptions: GTAxiosOptions

  constructor(options: GTAxiosOptions){
    this.axiosOptions = options
  }

  isSuccess(responseData: any){
    const { code } = responseData
    if(code === 0 || code === 200){
      return true
    }
    return false
  }

  commonFail(responseData: any){
    const { desc, msg, code } = responseData
    // if (code === 401 || code === 20012) {
    //   if(this.axiosOptions.response401){
    //     this.axiosOptions.response401()
    //   }
    //   return errorResult
    // }
    if(code === 20012 || code === 401 ) { // 会话过期
      if(this.axiosOptions.loginStatusCatch){
        this.axiosOptions.loginStatusCatch(code)
      }
    }else{
      if (desc || msg) {
        Toast.fail(desc || msg)
      }
    }

    return errorResult
  }

  addTokenToRequest(config: any){
    if(!config.headers){
      config.headers = {}
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      let uId = 0
      if(userInfo){
        const { userid } = JSON.parse(userInfo)
        uId = userid
      }
      config.headers['X-Bao-Session'] = token
      config.headers['X-Bao-Uid'] = uId
    }
  }
}

export default GTRequest
